package main

import (
	"github.com/streadway/amqp"
	"log"
	"rabbitmq"
)

func main() {
	conn := rabbitmq.NewConn()
	defer conn.Close()

	channel, err := conn.Channel()
	rabbitmq.FailOnError(err, "Channel err")

	q, err := channel.QueueDeclare("confirm_queue", false, false, false, false, nil)
	rabbitmq.FailOnError(err, "QueueDeclare err")

	//将信道设置为confirm模式
	if err := channel.Confirm(false); err != nil {
		rabbitmq.FailOnError(err, "Channel could not be put into confirm mode: %s")
	}
	//注册发布消息监听器
	confirms := channel.NotifyPublish(make(chan amqp.Confirmation, 1))

	go func() {
		log.Printf("wait publish confirmed")
		for confirm := range confirms {
			// 返回确认消息
			if confirm.Ack {
				// code when messages are confirmed
				log.Printf("Confirmed")
			} else {
				// code when messages are nack-ed
				log.Printf("Nacked")
			}
		}
	}()

	consume(channel, q.Name)
	publish(channel, q.Name, "wined")

	var forever chan struct{}
	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func consume(channel *amqp.Channel, qName string) {
	messages, err := channel.Consume(qName, "", true, false, false, false, nil)
	rabbitmq.FailOnError(err, "Consume err")

	go func() {
		for msg := range messages {
			log.Printf("Received a message: %s", msg.Body)
		}
	}()
}

func publish(channel *amqp.Channel, qName, text string) {
	err := channel.Publish("", qName, false, false, amqp.Publishing{
		ContentType: "text/plain",
		Body:        []byte(text),
	})
	rabbitmq.FailOnError(err, "Failed to publish a message")
}
